Fork me on GitHub

71. Simplify Path

\71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level. For more information, see: Absolute path vs relative path in Linux/Unix

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

Example 1:

1
2
3
Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

1
2
3
Input: "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.

Example 3:

1
2
3
Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:

1
2
Input: "/a/./b/../../c/"
Output: "/c"

Example 5:

1
2
Input: "/a/../../b/../c//.//"
Output: "/c"

Example 6:

1
2
Input: "/a//b////c/d//././/.."
Output: "/a/b/c"

乍眼一看可能觉得无从下手,甚至不知道怎么做。但是冷静下来就能发现规律。首先我们发现文件路径都是使用‘/’进行划分的,所以对于输入可以使用route = path.split('/')进行处理,同时也能处理掉多余的‘/’。然后我们发现出现“.”的时候,停留在当前路径;出现“..”的时候,回到上一层;出现“dirName”的时候,进入相应的dir。我们从中隐隐约约感觉到可以使用stack进行处理。对应关系如下:

出现“.”的时候,停留在当前路径:stack不变

出现“..”的时候,回到上一层:stack.pop()

出现“dirName”的时候,进入相应的dir:stack.append(dirName)

思路就出来了,然后需要注意一下edge case。比如stack为空的时候我们并不是什么都不输出,而是需要输出 ‘/’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
def simplifyPath(self, path: str) -> str:
if not path: return '/'
route = path.split('/')
stack = []
ans = ''
for d in route:
if d == "..":
if stack:
stack.pop()
continue
if d == '.':
continue
if d:
stack.append(d)
if not stack: return '/'
for d in stack:
ans += ('/' + d)
return ans

简化版,在处理输入时就排除空和’.’的情况

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def simplifyPath(self, path: str) -> str:
if not path: return '/'
route = [p for p in path.split('/') if p != "" and p != '.']
stack = []
for d in route:
if d == "..":
if stack:
stack.pop()
else:
stack.append(d)
return "/" + "/".join(stack)
Shuolin Tian wechat
欢迎加我微信交流